﻿#include "logger.h"
#include <cstdlib>
#include <chrono>
#include <ctime>
 
std::ofstream Logger::m_error_log_file;
std::ofstream Logger::m_info_log_file;
std::ofstream Logger::m_warn_log_file;
std::ofstream Logger::m_sensor_data_file;
 
void initLogger(const std::string& info_log_filename,
                const std::string& warn_log_filename,
               const std::string& error_log_filename){
   Logger::m_info_log_file.open(info_log_filename.c_str(),std::ios::app);
   Logger::m_warn_log_file.open(warn_log_filename.c_str(),std::ios::app);
   Logger::m_error_log_file.open(error_log_filename.c_str(),std::ios::app);
}

void initSensorDataLogger(const std::string& sensor_data_filename)
{
    Logger::m_sensor_data_file.open(sensor_data_filename.c_str(),std::ios::app);
}

std::ostream& Logger::getStream(log_rank_t log_rank){
   return (INFO == log_rank) ?
                (m_info_log_file.is_open() ?m_info_log_file : std::cout) :
                (WARNING == log_rank ?
                    (m_warn_log_file.is_open()? m_warn_log_file : std::cerr) :
                    (SENSOR_DATA == log_rank?
                         (m_sensor_data_file.is_open()? m_sensor_data_file : std::cerr):
                         (m_error_log_file.is_open()? m_error_log_file : std::cerr)));
}
void getFormatTime(char *res)
{
    std::time_t timep;
    std::tm *now;
    std::time(&timep);
    now = std::localtime(&timep); /* 获取当前时间 */
    // char res[15];// 多一位自动补零，再windows环境中才能正常运行
    sprintf(res, "%4d%02d%02d%02d%02d%02d:", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday
        , now->tm_hour, now->tm_min, now->tm_sec);
}
std::ostream& Logger::start(log_rank_t log_rank,
                            const int line,
                            const std::string& function) {
	//std::time_t ti = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
	//std::tm* now = std::gmtime(&ti);
    char res[15];
    getFormatTime(res);
   return getStream(log_rank) << res
                               << "function (" << function << ")"
                               << "line " << line<<": "
                               <<std::flush;
}
std::ostream& Logger::startSensor(log_rank_t log_rank) {
    //std::time_t ti = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    //std::tm* now = std::gmtime(&ti);
   char res[15];
   getFormatTime(res);
   return getStream(log_rank) << res<<std::flush;
}

Logger::~Logger(){
   getStream(m_log_rank) << std::endl << std::flush;
   
   if (FATAL == m_log_rank) {
       m_warn_log_file.close();
       m_info_log_file.close();
       m_error_log_file.close();
       m_sensor_data_file.close();
       abort();
    }

}
